var gulp = require('gulp');
var uglify = require('gulp-uglify');
var htmlreplace = require('gulp-html-replace');
var notify = require('gulp-notify');
var source = require('vinyl-source-stream');
var buffer     = require('vinyl-buffer');
var streamify = require('gulp-streamify');
var browserify = require('browserify');
var watchify = require('watchify');
var reactify = require('reactify');
var babelify   = require('babelify');
var lrload  = require('livereactload');
var browserSync = require('browser-sync').create();
var glob = require('glob');
var es = require('event-stream');
var rename = require('gulp-rename');

var path = {
    HTML: 'src/*.html',
    CSS:  'src/css/*.css',
    MINIFIED_OUT: 'build.min.js',
    OUT: 'build.js',
    DEST: 'dist/',
    DEST_BUILD: 'dist/build/',
    DEST_JS: 'dist/js/',
    DEST_CSS: 'dist/css/',
    ENTRY_POINT: 'front'
};

//复制HTML
gulp.task('html', function(){
    return gulp.src(path.HTML)
                .pipe(gulp.dest(path.DEST))
});


gulp.task('css', function(){
    return gulp.src(path.CSS)
                .pipe(gulp.dest(path.DEST_CSS))
                .pipe(browserSync.stream());
});

function handleErrors() {
    var args = Array.prototype.slice.call(arguments);
    notify.onError({
        title: "Compile Error",
        message: "<%= error.message %>"
    }).apply(this, args);
    this.emit('end'); // Keep gulp from hanging on this task
}

gulp.task('watch', function() {
    //监视html
    gulp.watch(path.HTML, ['html']).on('change', browserSync.reload);
    gulp.watch(path.CSS, ['css']);
    lrload.listen();
    var scanModules = glob('./src/js/*/index*.js', function(err, files) {
        var tasks = files.map(function(entry) {
            var moduleName = entry.split('/').reverse()[1];
            var fileName = entry.substring(entry.lastIndexOf('/')+1);
            console.log('add module:', moduleName, fileName,entry);
            var b = browserify({
                                entries: [entry],
                                transform: [babelify, lrload],
                                debug: false,
                                cache: {},
                                packageCache: {},
                                fullPaths: true
                            });
            watchify(b)
                .on('update', function() {
                    var start = Date.now();
                    this.bundle()
                        .on('error', handleErrors)
                        .pipe(source(fileName))
                        .pipe(rename({
                            extname: '.dev.js'
                        }))
                        .pipe(gulp.dest(path.DEST_JS + moduleName))
                        .pipe(lrload.gulpnotify())
                        .pipe(notify(function() {
                            console.log('[module=>  ' + moduleName + '] Updated，dev built in ' + (Date.now() - start) + 'ms');
                        }));
                }).emit('update')
        });
    });
});

//压缩，发布
gulp.task('build', function(){
    var scanModules = glob('./src/js/*/index*.js', function(err, files) {
        var tasks = files.map(function(entry) {
            var moduleName = entry.split('/').reverse()[1];
            var fileName = entry.substring(entry.lastIndexOf('/')+1);
            console.log('build module:', moduleName, '  entry=>',entry);
            browserify({
                    entries: [entry],
                    transform: [babelify],
                })
                .bundle()
                .on('error', handleErrors)
                .pipe(source(fileName))
                .pipe(streamify(uglify()))
                .pipe(rename({
                    extname: '.min.js'
                }))
                .pipe(gulp.dest(path.DEST_BUILD + moduleName));
            })
    });
});

//安装引用
gulp.task('bower', function() {
        gulp.src('src/vendor/**/*.{js,css,eot,svg,ttf,woff,woff2,map}', {base: 'app/bower_components'})
            .pipe(gulp.dest('dist/vendor/'));
});

//替换html javascript节点
gulp.task('replaceHTML', function(){
    gulp.src(path.HTML)
        .pipe(htmlreplace({
            'js': 'src/'+ path.OUT
        }))
        .pipe(gulp.dest(path.DEST));
});

//启动服务器，自动刷新更改
gulp.task('server',function(){
    browserSync.init({
        server: {
                baseDir: "./dist/"
        }
    });
})

gulp.task('production', ['build']);

gulp.task('default', ['html','css','watch','server']);


